package com.scorpio.security.common;

import com.github.pagehelper.PageHelper;
import com.scorpio.agentuser.domain.AgentUserEntity;
import com.scorpio.agentuser.service.AgentUserService;
import com.scorpio.agentuser.vo.PassLoginVo;
import com.scorpio.common.core.domain.Result;
import com.scorpio.common.exception.CustomException;
import com.scorpio.common.utils.security.SecurityUtils;
import com.scorpio.security.user.LoginUser;
import com.scorpio.security.service.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/api")
public class LoginController {
    private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private TokenService tokenService;

    @Autowired
    private AgentUserService personalService;

    @PostMapping("passLogin")
    public Result passLogin(@Validated @RequestBody PassLoginVo vo) {
        PageHelper.startPage(1, 1, "create_time desc");
        AgentUserEntity entity = personalService.selectByPhone(vo.getUsername());
        if (entity == null) {
            entity = personalService.selectByUsername(vo.getUsername());
        }
        if (entity == null) {
            throw new CustomException("帐号或密码有误");
        } else if (!SecurityUtils.matchesPassword(vo.getPassword(), entity.getPassword())) {
            throw new CustomException("帐号或密码有误");
        } else if (!"0".equals(entity.getStatus())) {
            throw new CustomException("手机帐号已停用");
        }
        LoginUser loginUser = new LoginUser("" + entity.getId());
        String token = tokenService.createToken(loginUser);
        tokenService.strongBackOperation("" + loginUser.getUniqueId(), loginUser.getToken());
        return Result.success(token);
    }

}
